from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework import serializers
from user.models import SysUser
from role.models import SysRole
from menu.models import SysMenu, SysMenuSerializer

# ✅ 1. 用户信息序列化器（放上面）
class SysUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = SysUser
        fields = ['id', 'username', 'avatar','email','phonenumber','create_time']  # 按需添加字段

class SysUserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SysUser
        fields = ['email', 'phonenumber']  # 可扩展


class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        username = attrs.get("username")
        password = attrs.get("password")

        try:
            user = SysUser.objects.get(username=username)
        except SysUser.DoesNotExist:
            raise serializers.ValidationError("用户名错误")

        if user.password != password:
            raise serializers.ValidationError("密码错误")

        # 🔐 生成 Token
        refresh = RefreshToken.for_user(user)

        # ✅ 获取用户权限菜单（按角色）
        roleList = SysRole.objects.raw(
            f"SELECT id, name FROM sys_role WHERE id IN (SELECT role_id FROM sys_user_role WHERE user_id={user.id})"
        )

        # ✅ 拼接角色名，逗号隔开（你要加的关键逻辑）
        roles = ",".join([role.name for role in roleList])

        menuSet = set()
        for role in roleList:
            menuList = SysMenu.objects.raw(
                f"SELECT * FROM sys_menu WHERE id IN (SELECT menu_id FROM sys_role_menu WHERE role_id={role.id})"
            )
            for menu in menuList:
                menuSet.add(menu)

        def build_tree(menu_list):
            result = []
            for menu in menu_list:
                for e in menu_list:
                    if e.parent_id == menu.id:
                        if not hasattr(menu, "children"):
                            menu.children = []
                        menu.children.append(e)
                if menu.parent_id == 0:
                    result.append(menu)
            return result

        menuList = sorted(list(menuSet))
        menuTree = build_tree(menuList)
        serializerMenuList = [SysMenuSerializer(menu).data for menu in menuTree]

        return {
            "refresh": str(refresh),
            "access": str(refresh.access_token),
            "username": user.username,
            "menuList": serializerMenuList,  # ✅ 加入菜单数据
            "user": SysUserSerializer(user).data,  # ✅ 添加这行
            "roles": roles  # ✅ 最终把角色字符串也返回

        }
